package com.tckdq.tcc.exception;

import com.tckdq.tcc.enums.ErrorCodeEnum;
import com.tckdq.tcc.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.util.List;

@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public JsonResult ExceptionHandler(Exception e){
        e.printStackTrace();
        return JsonResult.errorEnum(ErrorCodeEnum.SYS_ERROR);
    }


    @ExceptionHandler(value = GlobalException.class)
    public JsonResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        log.error(e.getMessage());

        return JsonResult.error(e.getErrorMsg());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error(e.getMessage());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder();
        for (ObjectError allError : allErrors) {
            sb=sb.append(allError.getDefaultMessage());
        }
        return JsonResult.error(sb.toString());
    }

    /*catch (
    IOException e) {
        e.printStackTrace();
        throw new BusinessException("生成验证码失败！");*/

    @ExceptionHandler(value = IOException.class)
    public JsonResult getIOExceptionHandler(IOException e){
        e.printStackTrace();
        log.error(e.getMessage());
        return JsonResult.errorEnum(ErrorCodeEnum.IMGCODE_ERROR);
    }

    @ExceptionHandler(value = BusinessException.class)
    public JsonResult getBusinessExceptionHandler(BusinessException e){
        e.printStackTrace();
        log.error(e.getMessage());
        return JsonResult.error(e.getErrorMsg(),e.getErrorCode());
    }

}
